//
//  ViewController.m
//  EasyAddProject
//
//  Created by 薛. on 2023/8/16.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <SVProgressHUD/SVProgressHUD.h>
#import "Masonry.h"
@import YiJiaStudent;

@interface ViewController () <AVCaptureMetadataOutputObjectsDelegate, UITextFieldDelegate>

/// 是否是iPad设备
@property(nonatomic, assign) BOOL deviceIsPad;

/// 扫描框宽度
@property(nonatomic, assign) CGFloat scanViewWidth;

/// 输入框
@property(nonatomic, strong) UITextField *tokenField;

/// 扫描描述
@property(nonatomic, strong) UILabel *descLabel;

/// 扫描区域
@property(nonatomic, strong) UIView *scanView;

/// 扫描动画线
@property(nonatomic, strong) UIImageView *scanLine;

/// 按钮
@property(nonatomic, strong) UIButton *leftButton;

/// 按钮
@property(nonatomic, strong) UIButton *rightButton;

/// 扫描
@property(nonatomic, strong) AVCaptureSession *session;

@end

@implementation ViewController

//MARK: - controller
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
#if TARGET_OS_SIMULATOR
// 模拟器特定的代码
#else
    __weak typeof(self) weakSelf = self;
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
            __strong typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf checkAuth];
        });
    }];
#endif
   
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadUI];
}
//MARK: - 初始化
/// 初始化
- (void)loadUI {
    self.title = @"扫一扫";
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.tokenField.text = @"testStudent";
    
    self.descLabel.text = @"将二维码放入框内";
    self.scanLine.image = [UIImage imageNamed:@"easy_add_qrcode_line"];
    
    [self.leftButton setTitle:@"易加学生端" forState:UIControlStateNormal];
    [self.rightButton setTitle:@"易加教师端" forState:UIControlStateNormal];
    
    CGFloat angeleWidth = self.deviceIsPad ? 20 : 30;
    
    [self addScanAngle:CGPointMake(0, angeleWidth) point1:CGPointMake(0, 0) point2:CGPointMake(angeleWidth, 0)];
    [self addScanAngle:CGPointMake(self.scanViewWidth - angeleWidth, 0) point1:CGPointMake(self.scanViewWidth, 0) point2:CGPointMake(self.scanViewWidth, angeleWidth)];
    [self addScanAngle:CGPointMake(self.scanViewWidth, self.scanViewWidth - angeleWidth) point1:CGPointMake(self.scanViewWidth, self.scanViewWidth) point2:CGPointMake(self.scanViewWidth - angeleWidth, self.scanViewWidth)];
    [self addScanAngle:CGPointMake(angeleWidth, self.scanViewWidth) point1:CGPointMake(0, self.scanViewWidth) point2:CGPointMake(0, self.scanViewWidth - angeleWidth)];
}

/// 画直角
- (void)addScanAngle:(CGPoint)movePoint point1:(CGPoint)point1 point2:(CGPoint)point2 {
    UIBezierPath *path = [[UIBezierPath alloc] init];
    [path moveToPoint:movePoint];
    [path addLineToPoint:point1];
    [path addLineToPoint:point2];
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    layer.path = path.CGPath;
    layer.strokeColor = [UIColor whiteColor].CGColor;
    layer.fillColor = [UIColor clearColor].CGColor;
    layer.lineWidth = 5;
    [self.scanView.layer addSublayer:layer];
}

//MARK: - methods
/// 检查权限
- (void)checkAuth {
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusAuthorized) {
        if (![self.session isRunning]) {
            [self startScan];
        }
    } else {
        [SVProgressHUD showErrorWithStatus:@"相机权限未打开，不能扫描"];
    }
}

/// 开始扫描
- (void)startScan {
    
    if ([self.scanLine.layer animationForKey:@"scanline_animation"]) {
        CFTimeInterval pausedTime = [self.scanLine.layer timeOffset];
        self.scanLine.layer.speed = 1.0;
        self.scanLine.layer.timeOffset = 0.0;
        self.scanLine.layer.beginTime = 0.0;
        CFTimeInterval timeSincePause = [self.scanLine.layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
        self.scanLine.layer.beginTime = timeSincePause;
    } else {
        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
        animation.removedOnCompletion = NO;
        animation.fillMode = kCAFillModeForwards;
        animation.repeatCount = HUGE;
        animation.duration = 3;
        animation.fromValue = [NSValue valueWithCGPoint:CGPointMake(self.scanViewWidth / 2, 0)];
        animation.toValue = [NSValue valueWithCGPoint:CGPointMake(self.scanViewWidth / 2, self.scanViewWidth - 3)];
        [self.scanLine.layer addAnimation:animation forKey:@"scanline_animation"];
    }
    
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (![strongSelf.session isRunning]) {
            [strongSelf.session startRunning];
        }
    });
}

/// 结束扫描
- (void)stopScan {
    if ([self.scanLine.layer animationForKey:@"scanline_animation"]) {
        CFTimeInterval pausTime = [self.scanLine.layer convertTime:CACurrentMediaTime() fromLayer:nil];
        self.scanLine.layer.timeOffset = pausTime;
        self.scanLine.layer.speed = 0;
    }
    
    if ([self.session isRunning]) {
        [self.session stopRunning];
    }
}

/// 切换类型
- (void)buttonClick:(UIButton *)sender {
    if (sender.isSelected) {
        return;
    }
    sender.selected = !sender.isSelected;
    sender.layer.borderColor = [UIColor colorWithRed:93 / 255.0 green:121 / 255.0 blue:254 / 255.0 alpha:1].CGColor;
    if (self.leftButton == sender) {
        self.tokenField.text = @"testStudent";
        self.rightButton.selected = NO;
        self.rightButton.layer.borderColor = [UIColor colorWithRed:266 / 255.0 green:229 / 255.0 blue:234 / 255.0 alpha:1].CGColor;
    } else {
        self.tokenField.text = @"testTeacher";
        self.leftButton.selected = NO;
        self.leftButton.layer.borderColor = [UIColor colorWithRed:266 / 255.0 green:229 / 255.0 blue:234 / 255.0 alpha:1].CGColor;
    }
    
}

//MARK: - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)output didOutputMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    [self stopScan];
    if ([metadataObjects.firstObject isKindOfClass:[AVMetadataMachineReadableCodeObject class]]) {
        AVMetadataMachineReadableCodeObject *codeObject = metadataObjects.firstObject;
        if (self.leftButton.isSelected) {
            LYZH_WebContainerViewController *vc = [LYZH_WebContainerViewController loadWithToken:codeObject.stringValue];
            [self.navigationController pushViewController:vc animated:YES];
        } else {
            
        }
    }
}

//MARK: - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (self.leftButton.isSelected) {
        LYZH_WebContainerViewController *vc = [LYZH_WebContainerViewController loadWithToken:textField.text];
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        
    }
    [textField resignFirstResponder];
    return true;
}

//MARK: - 懒加载
/// 设备
- (BOOL)deviceIsPad {
    if (!_deviceIsPad) {
        _deviceIsPad = [UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad;
    }
    return _deviceIsPad;
}

/// 扫描区域宽度
- (CGFloat)scanViewWidth {
    if (!_scanViewWidth) {
        _scanViewWidth = [UIScreen mainScreen].bounds.size.width * 0.5;
    }
    return _scanViewWidth;
}

/// 输入框
- (UITextField *)tokenField {
    if (!_tokenField) {
        _tokenField = [[UITextField alloc] init];
        _tokenField.backgroundColor = [UIColor whiteColor];
        _tokenField.textColor = [UIColor blackColor];
        _tokenField.delegate = self;
        _tokenField.font = [UIFont systemFontOfSize:self.deviceIsPad ? 16 : 14];
        _tokenField.placeholder = @"点击按钮重置token前缀";
        [self.view addSubview:_tokenField];
        [_tokenField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.bottom.equalTo(self.descLabel.mas_top).mas_offset(self.deviceIsPad ? -40 : -20);
            make.width.mas_equalTo(self.scanViewWidth);
            make.height.mas_equalTo(self.deviceIsPad ? 50 : 40);
        }];
    }
    return _tokenField;
}

/// 扫描描述
- (UILabel *)descLabel {
    if (!_descLabel) {
        _descLabel = [[UILabel alloc] init];
        _descLabel.textColor = [UIColor whiteColor];
        _descLabel.font = [UIFont systemFontOfSize:self.deviceIsPad ? 16 : 14];
        [self.view addSubview:_descLabel];
        [_descLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.scanView.mas_top).mas_offset(- (self.deviceIsPad ? 30 : 20));
            make.centerX.equalTo(self.view);
        }];
    }
    return _descLabel;
}

/// 扫描区域
- (UIView *)scanView {
    if (!_scanView) {
        CGFloat scanX = [UIScreen mainScreen].bounds.size.width / 2 - self.scanViewWidth / 2;
        CGFloat scanY = [UIScreen mainScreen].bounds.size.height / 2 - self.scanViewWidth / 2;
        _scanView = [[UIView alloc] initWithFrame:CGRectMake(scanX, scanY, self.scanViewWidth, self.scanViewWidth)];
        [self.view addSubview:_scanView];
    }
    return _scanView;
}

/// 扫描动画线
- (UIImageView *)scanLine {
    if (!_scanLine) {
        _scanLine = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]];
        _scanLine.frame = CGRectMake(0, 0, self.scanViewWidth, 3);
        [self.scanView addSubview:_scanLine];
    }
    return _scanLine;
}

/// 按钮
- (UIButton *)leftButton {
    if (!_leftButton) {
        _leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _leftButton.selected = YES;
        [_leftButton setTitleColor:[UIColor colorWithRed:48 / 255.0 green:48 / 255.0 blue:48 / 255.0 alpha:1] forState:UIControlStateNormal];
        [_leftButton setTitleColor:[UIColor colorWithRed:93 / 255.0 green:121 / 255.0 blue:254 / 255.0 alpha:1] forState:UIControlStateSelected];
        _leftButton.titleLabel.font = [UIFont systemFontOfSize:self.deviceIsPad ? 16 : 14];
        _leftButton.layer.cornerRadius = self.deviceIsPad ? 12 : 8;
        _leftButton.layer.borderWidth = 1;
        _leftButton.layer.borderColor = [UIColor colorWithRed:93 / 255.0 green:121 / 255.0 blue:254 / 255.0 alpha:1].CGColor;
        _leftButton.clipsToBounds = YES;
        _leftButton.backgroundColor = [UIColor whiteColor];
        [_leftButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_leftButton];
        [_leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.scanView.mas_bottom).mas_offset(self.deviceIsPad ? 60 : 40);
            make.right.equalTo(self.view.mas_centerX).mas_offset(self.deviceIsPad ? -40 : -20);
            make.width.mas_equalTo(self.deviceIsPad ? 200 : 160);
            make.height.mas_equalTo(50);
        }];
    }
    return _leftButton;
}

/// 按钮
- (UIButton *)rightButton {
    if (!_rightButton) {
        _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _rightButton.selected = NO;
        [_rightButton setTitleColor:[UIColor colorWithRed:48 / 255.0 green:48 / 255.0 blue:48 / 255.0 alpha:1] forState:UIControlStateNormal];
        [_rightButton setTitleColor:[UIColor colorWithRed:93 / 255.0 green:121 / 255.0 blue:254 / 255.0 alpha:1] forState:UIControlStateSelected];
        _rightButton.titleLabel.font = [UIFont systemFontOfSize:self.deviceIsPad ? 16 : 14];
        _rightButton.layer.cornerRadius = self.deviceIsPad ? 12 : 8;
        _rightButton.layer.borderWidth = 1;
        _rightButton.layer.borderColor = [UIColor colorWithRed:266 / 255.0 green:229 / 255.0 blue:234 / 255.0 alpha:1].CGColor;
        _rightButton.clipsToBounds = YES;
        _rightButton.backgroundColor = [UIColor whiteColor];
        [_rightButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_rightButton];
        [_rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.scanView.mas_bottom).mas_offset(self.deviceIsPad ? 60 : 40);
            make.left.equalTo(self.view.mas_centerX).mas_offset(self.deviceIsPad ? 40 : 20);
            make.width.mas_equalTo(self.deviceIsPad ? 200 : 160);
            make.height.mas_equalTo(50);
        }];
    }
    return _rightButton;
}

/// 扫描
- (AVCaptureSession *)session {
    if (!_session) {
        _session = [[AVCaptureSession alloc] init];
        AVCaptureDevice *avDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:avDevice error:nil];
        AVCaptureMetadataOutput *deviceOutput = [[AVCaptureMetadataOutput alloc] init];
        
        [deviceOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
        
        
        if ([_session canAddInput:deviceInput]) {
            [_session addInput:deviceInput];
        }
        if ([_session canAddOutput:deviceOutput]) {
            [_session addOutput:deviceOutput];
        }
        [_session canSetSessionPreset:AVCaptureSessionPresetHigh];
        
        deviceOutput.metadataObjectTypes = @[AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeQRCode, AVMetadataObjectTypeCode128Code];

        CGFloat scanX = [UIScreen mainScreen].bounds.size.width / 2 - self.scanViewWidth / 2;
        CGFloat scanY = [UIScreen mainScreen].bounds.size.height / 2 - self.scanViewWidth / 2;
        CGFloat deviceWidth = [UIScreen mainScreen].bounds.size.width;
        CGFloat showHeight = [UIScreen mainScreen].bounds.size.height - self.navigationController.navigationBar.frame.size.height - [UIApplication sharedApplication].statusBarFrame.size.height;
        
        /// 相机展示区域
        AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_session];
        previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        previewLayer.frame = CGRectMake(0, (self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height), deviceWidth, showHeight);
        [self.view.layer insertSublayer:previewLayer atIndex:0];
        
        /// 扫码识别区域
        deviceOutput.rectOfInterest = CGRectMake(scanY / showHeight, (deviceWidth - self.scanViewWidth - scanX) / deviceWidth, self.scanViewWidth / showHeight, self.scanViewWidth / deviceWidth);
    }
    return _session;
}

@end
